/**
 * Framebuffer implemenation
 */

#include "Framebuffer.h"

GLenum Framebuffer::_buffers[] = {
	GL_COLOR_ATTACHMENT0_EXT,
	GL_COLOR_ATTACHMENT1_EXT,
	GL_COLOR_ATTACHMENT2_EXT,
	GL_COLOR_ATTACHMENT3_EXT,
	GL_COLOR_ATTACHMENT4_EXT };

#ifdef DEBUG
#define assertBind(name) assert(_bind(name));
#define assertComplete() // assert(_complete());
#else
#define assertBind(name)
#define assertComplete()
#endif

bool _bind(GLuint name) 
{
	GLint id;
	glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &id);
	return (name == (GLuint) id);
}

bool _complete()
{
	GLenum status; 
	status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	return (status == GL_FRAMEBUFFER_COMPLETE_EXT);
}


/////////////////////////////////////////////////

void Framebuffer::attachTexture(const TexturePtr& t, GLenum where)
{
	assert(t != 0);
	assertBind(_glName);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, where, t->getTarget(), t->getGLName(), 0);
	assertComplete();
	checkGLError();
}

/////////////////////////////////////////////////

void Framebuffer::attachRenderbuffer(const RenderbufferPtr& rb)
{
	assert(rb != 0);
	assertBind(_glName);
	// TODO this right?
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, rb->getTarget(), GL_RENDERBUFFER_EXT, rb->getGLName());
	assertComplete();
	checkGLError();
}
/////////////////////////////////////////////////

void Framebuffer::bind()
{
	assert(_glName);
	glGetIntegerv(GL_DRAW_BUFFER, &_savedDrawBuffer);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _glName);
	assertComplete();
	checkGLError();
}

/////////////////////////////////////////////////

void Framebuffer::drawBuffer(GLenum buf) 
{
	assertBind(_glName);
	glDrawBuffer(buf);
	assertComplete();
	checkGLError();
//	glDrawBuffers(_textures.size(), _buffers);
}

/////////////////////////////////////////////////

void Framebuffer::drawColorAttachments(GLuint num)
{
	assertBind(_glName);
	glDrawBuffers(num, _buffers);
	assertComplete();
	checkGLError();
}

/////////////////////////////////////////////////

void Framebuffer::unbind()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glDrawBuffer(_savedDrawBuffer);
	checkGLError();
}

/////////////////////////////////////////////////


